import os
from flask import Flask, render_template, request, jsonify, abort

app = Flask(__name__)
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
WORK_DIR = os.path.join(BASE_DIR, 'workspace')  # 设置工作目录

def safe_path(path):
    """验证路径安全性"""
    full_path = os.path.abspath(os.path.normpath(os.path.join(WORK_DIR, path.lstrip('/'))))
    if not full_path.startswith(WORK_DIR):
        abort(403)
    return full_path

@app.route('/')
def index():
    path = request.args.get('path', '')
    full_path = safe_path(path)

    if not os.path.exists(full_path):
        return "路径不存在", 404

    if os.path.isfile(full_path):
        return "请访问目录路径", 400

    # 获取目录内容
    items = []
    for item in os.listdir(full_path):
        item_path = os.path.join(full_path, item)
        items.append({
            'name': item,
            'is_dir': os.path.isdir(item_path),
            'size': os.path.getsize(item_path)
        })

    return render_template('index.html',
                         items=items,
                         current_path=path,
                         parent_dir=os.path.dirname(path))

@app.route('/file')
def get_file():
    file_path = request.args.get('path')
    if not file_path:
        return "缺少路径参数", 400

    full_path = safe_path(file_path)

    if not os.path.isfile(full_path):
        return "不是文件", 400

    try:
        with open(full_path, 'r', encoding='utf-8') as f:
            content = f.read()
        return jsonify({
            'content': content,
            'path': file_path
        })
    except Exception as e:
        return str(e), 500

@app.route('/save', methods=['POST'])
def save_file():
    data = request.json
    file_path = data.get('path')
    content = data.get('content')

    if not file_path or content is None:
        return "参数错误", 400

    full_path = safe_path(file_path)

    try:
        with open(full_path, 'w', encoding='utf-8') as f:
            f.write(content)
        return jsonify({'status': 'success'})
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500

if __name__ == '__main__':
    os.makedirs(WORK_DIR, exist_ok=True)
    app.run(debug=True)
